﻿#pragma strict
var startPoint:Vector3;
var movePoint:Vector3;
var endPoint:Vector3;
var showDistance:float = 0.0;
var Distance:float = 0.0;
var isStart:boolean;
var isOver:boolean;
var isFollow:boolean;
var mLine:LineRenderer;
var aMaterial:Material;
var mx:float = 0.0;
var my:float = 0.0;
var i:int=0;
var k:int=1;

function Start (){
    mLine = this.gameObject.AddComponent(LineRenderer);
    mLine.SetWidth(4,4);
    mLine.SetVertexCount(k);
    mLine.SetColors (Color.yellow,Color.yellow);
    mLine.material = aMaterial;
    //mLine.material.color = Color (0, 1, 0, 0.25);
    mLine.material.color = Color.red;
    mLine.renderer.enabled = true;
}

function Update () {
    if (Input.GetButtonDown("Fire1")) {
        startPoint = Vector3.zero;
        isFollow = true;
        showDistance=showDistance+Distance;
        
        var sRay = camera.ScreenPointToRay (Input.mousePosition);
        var sHit : RaycastHit;
        if (Physics.Raycast (sRay,sHit)) {
            startPoint = sHit.point;
            print("startPoint:" +sHit.point);
            mLine.SetPosition(i++,startPoint);
            mLine.SetVertexCount(++k);
            isStart = true;
            isOver = false;
        }else{
            print("");
        }
    }

    if(isStart && !isOver){
        var mRay = camera.ScreenPointToRay (Input.mousePosition);
        var mHit : RaycastHit;
        isFollow = true;
        
        if (Physics.Raycast (mRay,mHit)) {
            movePoint = mHit.point;
            print("mPoint:" +mHit.point);
            mLine.SetPosition(i,movePoint);
            Distance=Vector3.Distance(movePoint,startPoint);
        }else{
            print("");
        }
    }
    
    if (Input.GetButtonDown("Fire2")) {
        var eRay = camera.ScreenPointToRay (Input.mousePosition);
        var eHit : RaycastHit;
        isFollow = false;
        showDistance =showDistance+Distance;
        
        if (Physics.Raycast(eRay,eHit)) {
            endPoint = eHit.point;
            print("endPoint:" +eHit.point);
            isOver = true;
            isStart = false;
            Distance= Vector3.Distance(endPoint,startPoint);
            mLine.SetPosition(i,endPoint);
        }else{
            print("");
        }
    }
}

function OnGUI () {
    if(isFollow){
        mx = Input.mousePosition.x + 5;
        my = Screen.height-Input.mousePosition.y - 20;
        GUI.Label(Rect (mx,my, 100, 20), Distance.ToString() + " M");
    }else{
        GUI.Label(Rect (mx,my, 100, 20), showDistance.ToString() + " M");
    }
}